package cn.itcast.dao;

import cn.itcast.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author: HuYi.Zhang
 * @create: 2018-07-12 17:04
 **/
@Component
public class UserDao {

    @Autowired
    private RestTemplate restTemplate;

//    @Autowired
//    private DiscoveryClient discoveryClient;

    @HystrixCommand(fallbackMethod = "queryByIdFallback")
    public User queryById(Long id) {
        // List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        // 编写负载均衡算法，从实例集合中，获取某个实例。轮询、随机、hash、加权
//        ServiceInstance instance = instances.get(0);
//        String host = instance.getHost();
//        int port = instance.getPort();
//        String url = "http://" + host + ":" + port + "/user/" + id;

        String url = "http://user-service/user/" + id;
        return this.restTemplate.getForObject(url, User.class);
    }

    public User queryByIdFallback(Long id) {
        User user = new User();
        user.setId(0L);
        user.setName("用户信息查询异常！");
        return user;
    }
}
